package com.yihaodian.common.threadpool;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.collect.ImmutableMap;

/**
 * TODO, add configuration, add stats.
 * 
 */
public class ThreadPool {

	private volatile ImmutableMap<String, Executor> executors;

	public static class Names {
		public static final String INDEX = "index";
		public static final String SEARCH = "search";
		public static final String FLUSH = "flush";
		public static final String MERGE = "merge";
	}

	static Map<String, Integer> poolSize = new HashMap<String, Integer>() {
		{
			this.put(Names.INDEX, 1);
			this.put(Names.SEARCH, 100);
			this.put(Names.FLUSH, 2);
			this.put(Names.MERGE, 2);
		}
	};

	Timer timer = new Timer("DefaultTimer", true);

	public Timer getTimer() {
		return timer;
	}

	public Executor executor(String name) {
		Executor executor = executors.get(name);
		if (executor == null) {
			// cached
			executor = build(0, Integer.MAX_VALUE, 60 * 10000,
					TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>());
		}
		return executor;
	}

	private ThreadPoolExecutor build(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
		return new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
				keepAliveTime, unit, workQueue);
	}
}
